<!-- 结合usePagination这个hooks，把需要分页加载数据的模块都封装在一起 -->
<template>
  <div>
    <slot name="top"
          :total="paginationState.total"></slot>
    <van-pull-refresh v-model="loadingState.pullDownLoading"
                      @refresh="reload">
      <van-list v-model:loading="loadingState.infiniteLoading"
                :finished="loadingState.isNoMore"
                :immediate-check="immediately"
                :finished-text="immediately ? '没有更多了' : ''"
                @load="loadNextPage">
        <slot :list="paginationState.list"
              v-if="paginationState.list.length > 0"></slot>
        <Empty v-else />
      </van-list>
    </van-pull-refresh>
  </div>

</template>

<script setup>
import { usePagination } from '@/hooks/usePagination'

const props = defineProps({
  // 分页加载数据的service方法
  service: {
    type: Function,
    default: () => {}
  },
  // 发起请求前对请求参数的处理
  beforeRequest: {
    type: Function,
    default: null
  },
  // 请求响应后对返回数据
  afterRequest: {
    type: Function,
    default: null
  },
  // 分页加载的请求参数
  params: {
    type: Object,
    default: () => ({})
  },
  // 分页请求时的page字段名，如有的分页接口page叫current
  pageKey: {
    type: String,
    default: 'page'
  },
  // 分页请求时的size字段名，如有的分页接口size叫limit
  sizeKey: {
    type: String,
    default: 'size'
  },
  // 有的接口主要请求参数不是是根对象上，而是在嵌套对象上
  paramsKey: {
    type: String,
    default: ''
  },
  // 是否立即执行接口请求
  immediately: {
    type: Boolean,
    default: true
  }
})
const { paginationState, reload, loadNextPage, loadingState } = usePagination({
  loadPageFunc: props.service,
  params: props.params,
  pageKey: props.pageKey,
  sizeKey: props.sizeKey,
  paramsKey: props.paramsKey,
  beforeRequest: props.beforeRequest,
  afterRequest: props.afterRequest
})

// 对外公开一个重新加载的方法
defineExpose({
  reload,
  paginationState
})
</script>
